package com.strongbj.iot.devices.amazondb.request.handle;

import java.util.Map;
import java.util.Set;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.amazondb.request.message.MQBodyMessage;
import com.strongbj.iot.mq.producer.TopicSender;

public class PushInventoryToMQRunnable implements Runnable {
	private final static Logger logger = LogManager.getLogger(PushInventoryToMQRunnable.class);
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	private static final String TOPIC_NAME = "daio";
	private final static String ACTION_CODE_RETURN = "inventoryTagReturn";
	private String guid;
	private String[] readerCodes;
	private Set<String> onlineLabs;
	private Set<String> offlineLabs;
	private Map<String, Set<String>> tagsMap;

	public PushInventoryToMQRunnable(String guid, String[] readerCodes, Map<String, Set<String>> tagsMap) {
		this.guid = guid;
		this.readerCodes = readerCodes;
		this.tagsMap = tagsMap;
	}

	@Override
	public void run() {
		try {

			this.onlineLabs = tagsMap.get(guid + "_online");
			this.offlineLabs = tagsMap.get(guid + "_offline");
			this.offlineLabs.removeAll(this.onlineLabs); // 从离线里移除所有在线里有的标签
			JSONObject object = new JSONObject();
			object.put("readerCode", readerCodes);
			object.put("onlineLabs", onlineLabs);
			object.put("offlineLabs", offlineLabs);
			MQBodyMessage<JSONObject> msg = new MQBodyMessage<>();
			msg.setActioncode(ACTION_CODE_RETURN);
			msg.setGUID(this.guid);
			msg.setPostdata(object);
			String json = JSON.toJSONString(msg);
			topicSender.send(TOPIC_NAME, json);

			logger.info("上传盘点数据到MQ完成,盘到标签{}个，未盘到标签{}个，JSON={}", this.onlineLabs.size(), this.offlineLabs.size(), json);
		} finally {
			tagsMap.remove(guid + "_online");
			tagsMap.remove(guid + "_offline");
		}

	}

}
